package com.lg.happyfarmer.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hemaapp.hm_FrameWork.HemaNetTask;
import com.hemaapp.hm_FrameWork.result.HemaBaseResult;
import com.lg.happyfarmer.R;
import com.lg.happyfarmer.base.BaseActivity;
import com.lg.happyfarmer.base.BaseApplication;
import com.lg.happyfarmer.base.BaseUtil;
import com.lg.happyfarmer.snackbar.BaseTransientBottomBar;
import com.lg.happyfarmer.snackbar.TopSnackBar;
import com.lg.happyfarmer.untils.UserUtils;

import java.io.IOException;

import butterknife.Bind;
import butterknife.ButterKnife;
import pl.droidsonroids.gif.GifDrawable;
import pl.droidsonroids.gif.GifImageView;
import xtom.frame.util.XtomSharedPreferencesUtil;

/**
 * 验证码验证
 * Created by Torres on 2018/3/30 0030.
 */

public class CodeVerifyActivity extends BaseActivity implements View.OnClickListener {
    @Bind(R.id.ib_back)
    ImageButton ib_back;
    @Bind(R.id.btn_test)
    Button btn_test;
    @Bind(R.id.ed_code)
    EditText ed_code;
    @Bind(R.id.tv_resend)
    TextView tv_resend;
    @Bind(R.id.tv_second)
    TextView tv_second;
    @Bind(R.id.tv_flag)
    TextView tv_flag;
    @Bind(R.id.ll_time)
    LinearLayout ll_time;
    @Bind(R.id.iv_tip)
    GifImageView iv_tip;

    private String phone;
    private TimeThread timeThread;
    private int temp;
    @Bind(R.id.ll_all)
    LinearLayout ll_all;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_codeverify);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
        BaseUtil.startLayoutAnim(mContext,ll_all);

        if(isNull(BaseApplication.phone) || !BaseApplication.phone.equals(phone)){

            timeThread = new TimeThread(new TimeHandler(this),60);
            timeThread.start();
            BaseApplication.phone=phone;
            TopSnackBar.make(ed_code, "验证码已发送到"+phone, BaseTransientBottomBar.LENGTH_LONG).show();
        }else if(BaseApplication.phone.equals(phone)){
            timeThread = new TimeThread(new TimeHandler(this),BaseApplication.time);
            timeThread.start();
        }
        BaseUtil.showKeyBoard(ed_code);
    }


    @Override
    protected void onDestroy() {
        if (timeThread != null)
            timeThread.cancel();

        super.onDestroy();
    }
    @Override
    protected void callBeforeDataBack(HemaNetTask netTask) {
        super.callBeforeDataBack(netTask);
    }

    @Override
    protected void callAfterDataBack(HemaNetTask netTask) {
        super.callAfterDataBack(netTask);
    }

    @Override
    protected void callBackForServerSuccess(HemaNetTask netTask, HemaBaseResult baseResult) {
        super.callBackForServerSuccess(netTask, baseResult);
    }

    @Override
    protected void callBackForServerFailed(HemaNetTask netTask, HemaBaseResult baseResult) {
        super.callBackForServerFailed(netTask, baseResult);
    }

    @Override
    protected void callBackForGetDataFailed(HemaNetTask netTask, int failedType) {
        super.callBackForGetDataFailed(netTask, failedType);
    }

    @Override
    protected void findView() {
        super.findView();
    }

    @Override
    protected void getExras() {
        super.getExras();
        phone=mIntent.getStringExtra("phone");
    }

    @Override
    protected void setListener() {
        super.setListener();
        ib_back.setOnClickListener(this);
        tv_resend.setOnClickListener(this);
        btn_test.setOnClickListener(this);
        ed_code.addTextChangedListener(new TextWatcher() {

            private boolean isDelete;
            @Override
            public void onTextChanged(CharSequence s, int cursorPosition, int before, int count) {
                ed_code.setOnKeyListener(new View.OnKeyListener() {

                    @Override
                    public boolean onKey(View v, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_DEL) {
                            isDelete = true;
                        }
                        return false;
                    }
                });
            }
            @Override
            public void afterTextChanged(Editable arg0) {
                if(arg0.toString().length()==4){

                    if(arg0.toString().equals("1234")){

                        ll_time.setVisibility(View.GONE);
                        try {
                            GifDrawable gifDrawable1 = new GifDrawable(getResources(), R.drawable.icon_correctgif);
                            iv_tip.setImageDrawable(gifDrawable1);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                BaseApplication.phone="";
                                Intent it=new Intent(mContext,SexSelectActivity.class);
                                startActivity(it);
                                finish();
                            }
                        },2000);
                        btn_test.setEnabled(true);
                    }else{
                        TopSnackBar.make(ed_code, "验证码错误", BaseTransientBottomBar.LENGTH_LONG).show();
//                        ll_time.setVisibility(View.VISIBLE);
                        btn_test.setEnabled(false);
                    }
                }


            }
            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,int arg2, int arg3) {
            }
        });


    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ib_back:
                BaseApplication.time=temp;
                BaseApplication.getInstance().startTimer(temp);
                finish();
                break;
            case R.id.tv_resend:
                tv_resend.setVisibility(View.GONE);
                ll_time.setVisibility(View.VISIBLE);
                tv_second.setVisibility(View.VISIBLE);
                tv_flag.setVisibility(View.VISIBLE);
                timeThread = new TimeThread(new TimeHandler(this),60);
                timeThread.start();
                TopSnackBar.make(ed_code, "验证码已发送到"+phone, BaseTransientBottomBar.LENGTH_LONG).show();


                break;
            case R.id.btn_test:
                BaseApplication.phone="";
                Intent it=new Intent(mContext,SexSelectActivity.class);
                startActivity(it);
                finish();
                break;
        }
    }


    private class TimeThread extends Thread {
        private int curr;

        private TimeHandler timeHandler;

        public TimeThread(TimeHandler timeHandler,int curr) {
            this.timeHandler = timeHandler;
            this.curr=curr;

        }

        void cancel() {
            curr = 0;
        }

        @Override
        public void run() {
//            curr = 60;
            while (curr > 0) {
                timeHandler.sendEmptyMessage(curr);
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // ignore
                }
                curr--;
            }
            timeHandler.sendEmptyMessage(-1);
        }
    }

    private static class TimeHandler extends Handler {
        CodeVerifyActivity activity;

        public TimeHandler(CodeVerifyActivity activity) {
            this.activity = activity;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case -1:
                    activity.tv_second.setVisibility(View.GONE);
                    activity.tv_flag.setVisibility(View.GONE);
                    activity.tv_resend.setText("重新发送");
                    activity.tv_resend.setVisibility(View.VISIBLE);
                    activity.temp=0;
                    break;
                default:
                    activity.tv_second.setText(""+msg.what);
                    activity.temp=msg.what;
                    break;
            }
        }
    }

    @Override
    protected boolean onKeyBack() {
        BaseApplication.time=temp;
        BaseApplication.getInstance().startTimer(temp);
        return super.onKeyBack();
    }
}
